package com.yecheng.yeaiagent.tools;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TerminalOperationTools {

    @Tool(description = "Execute commands in the console")
    public String executeCommand(@ToolParam(description = "The command to execute in the console") String command) {
        StringBuilder stringBuilder = new StringBuilder();
        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
        try {
            Process process = processBuilder.start();
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"))){
                String line;
                while((line = bufferedReader.readLine()) != null){
                    stringBuilder.append(line).append("\n");
                }
            }
            int exitCode = process.waitFor();
            if(exitCode != 0){
                stringBuilder.append("Command execution failed, exit code: ").append(exitCode);
            }
        } catch (IOException | InterruptedException e) {
            stringBuilder.append("Command execution failed:").append(e.getMessage());
        }
        return stringBuilder.toString();
    }
}
